import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router'
import { Hero } from './hero'
import {HeroService} from './hero.service'
//import { heroServiceProvider } from './hero.service.provider';
@Component({
    selector: 'my-heros',
    template: require('./heros.html'),
    styles: [require("./heros.css")],
    //providers:[heroServiceProvider]
})
export class HerosComponent implements OnInit {
    heros: Hero[];
    selectedHero: Hero;
    constructor(private heroService: HeroService,
        private router: Router) {

    }
    onSelect(hero: Hero): void {
        console.log('trigger onSelect function:%O', hero)
        this.selectedHero = hero;
    }

    ngOnInit() {
        this.heroService.getHeros().then(heros => this.heros = heros)
    }

    gotoDetail(id: number): void {
        if (!id) {
            id = this.selectedHero.id;
        }
        this.router.navigate(['/detail', id])
    }


    add(name: string) {
        name = name.trim();
        if (!name) return;
        this.heroService.create(name).then(
            hero => {
                this.heros.push(hero)
                this.selectedHero = null;
            }
        )
    }

    delete(hero: Hero): void {
        this.heroService
            .delete(hero.id)
            .then(() => {
                this.heros = this.heros.filter(h => h !== hero);
                if (this.selectedHero === hero) { this.selectedHero = null; }
            });
    }

}
